<?php
namespace app\siteadmin\controller;

use app\siteadmin\service\AdminLoginService;
use app\BaseController;
use app\Response;
use think\facade\Cache;
use think\facade\Request;

class AdminLogin extends BaseController
{
    public function login(){
        if(Request::method() == 'POST'){
            $data = Request::param();//account 与 password
            try{
                $this->validate($data, 'LoginCheck');
            }catch (\Exception $e){
                return Response::wrapError(0,$e->getMessage());
            }
            $res = AdminLoginService::login($data);
            return $res;
        }
    }


    //获取session
    public function user_session($name='uid'){

        $session = session($name);
        if($session){
            echo $session;
        }
        else{
            echo 0;
        }
    }

    //退出
    public function user_exit(){
        Session::clear();
    }


    public function head(){
        $username = session('username');

        $user_type = session('type');

        $data['u_name'] = $username;
        $data['u_type'] = $user_type;
        echo  json_encode($data);
    }

    /**
     * 生成随机字符串
     * @param int $user_id
     * @param array $data
     * @return string
     */
    public static function str_random($length = 16)
    {
        $string = '';
        while (($len = strlen($string)) < $length) {
            $size = $length - $len;
            $bytes = random_bytes($size);
            $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
        }
        return $string;
    }
}